<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/18 0018
 * Time: 12:23
 */
namespace app\admin\controller;
use houdunwang\middleware\Middleware;

class Category extends Common
{
   protected $db;

    /**
     * 连接数据库
     */
       public function __init()
       {
           $this->db= new \system\model\Category();
       }

    /** 首页
     * @return mixed
     */
    public function index(){
     $data=Db::table('category')->get();
     //数组增强
      $data = Arr::tree($data,'cname');
      View::with('data',$data);
     return view();
   }

    /**
     * 添加顶级分类
     * @return mixed
     */
   public function store(){
     if(IS_POST){
         if($this->db->store()){
             message('顶级分类添加成功',u('index'),'success',2);
         }
         message('顶级分类添加失败','back','error',2);
     }
     return view();
   }
   /**
    * 添加子集分类
    */
   public function addSon(){
       if(IS_POST){
           if($this->db->store()){
               message('子级分类添加成功',u('index'),'success',2);
           }
           message('子级分类添加失败','back','error',2);
       }
       $cid=q('get.cid');
       $data=Db::table('category')->find($cid);
       //分配变量
       View::with('data',$data);
       return view();
   }
   /**
    * 编辑分类
    *
    */
   public function  edit(){
        if(IS_POST){
            if($this->db->edit()){
                message('编辑分类成功',u('index'),2);
            }
            message('编辑分类失败','back',2);
        }
        $cid=q('get.cid');
        $data=Db::table('Category')->find($cid);
        View::with('data',$data);
        //处理分类标题
        $cateData=$this->db->getCateDate($cid);
//        p($cateData);
        View::with('cateData',$cateData);
       return view();
   }
   public function del(){
       $cid=q('get.cid');
       $pid=$this->db->where('cid',$cid)->pluck('pid');
        //       $data=Db::table('category')->get();
        //       $res= $this->db->del($cid,$data);
       //修改子集分类
        $this->db->where('pid',$cid)->update(['pid'=>$pid]);
      //删除
       $res=$this->db->where('cid',$cid)->delete();
       if(!$res){
           message('删除失败','back','error',2);
       }
       message('删除成功',u('admin.category.index'),'success',2);
   }
}